package com.tlgen.controller;

import com.google.zxing.WriterException;
import com.tlgen.util.QRCodeGenerator;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 生成和访问二维码
 */
@RestController
@RequestMapping("/qrcode")
public class QRcodeController {

    @Value("${file.upload.path}")
    private String uploadPath;

    SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");

    @GetMapping
    public Map<String, Object> getQRcode(HttpServletRequest request) throws IOException, WriterException {

        HashMap<String, Object> map = new HashMap<>();

        String newName = UUID.randomUUID().toString() + ".png";

        // 生成二维码
        /**
         * 二维码的text内容是一个链接地址的时候 用手机浏览器扫后会自动跳转进入对应链接地址
         * 要想实现手机扫描后通知前端, 那么就得需要一个公网访问的网页链接, 链接中的操作通过公网ip地址给后端回调地址发送post、put请求
         * 后端在回调接口中处理业务使用 websocket 主动向前端发送通知状态即可
         */
        QRCodeGenerator.generateQRCodeImage("http://124.70.180.155:8081", 350, 350, uploadPath + newName);

        // 服务器访问 文件上传
        File file = new File(uploadPath + newName);

        // 将java.io.File转为MultipartFile
        FileInputStream inputStream = new FileInputStream(file);
        MockMultipartFile multipartFile = new MockMultipartFile("file", file.getName(), "text/plain", IOUtils.toByteArray(inputStream));
        System.out.println("将java.io.File转为MultipartFile成功后文件为:" + multipartFile);

        String format = sdf.format(new Date());
        String realPath = request.getServletContext().getRealPath("/") + format;

        File folder = new File(realPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }

        try {
            multipartFile.transferTo(new File(folder, newName));
            String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + format + newName;
            System.out.println(url);
            map.put("msg", "二维码生成成功!");
            map.put("url", url);
        } catch (Exception e) {
            map.put("msg", "二维码生成失败!");
        }
        return map;
    }

}
